package ltd.followkba.comment.banners;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import ltd.advskin.beandbs.BSaveBean;
import ltd.advskin.beandbs.ConvBean;

public class CBeanFile extends SQLiteOpenHelper {
    SQLiteDatabase mSQLiteDatabase;
    //    private String gsFileName;
    public String gsTable;
    public boolean isLongItem;

    public CBeanFile(Context context, String fileName, String table, boolean longItem) {
        super(context, fileName, null, 1);
//        gsFileName = fileName;
        gsTable = table;
        isLongItem = longItem;
//        if (MRAM.mSQLiteDatabase != null && MRAM.mSQLiteDatabase.isOpen()){
//            MRAM.mSQLiteDatabase.close();
//        }
        mSQLiteDatabase = getWritableDatabase();
        String gsLocal_1 = (isLongItem ? "text" : "integer") + ", bean text)";
        mSQLiteDatabase.execSQL(String.format("create table if not exists %s (id integer primary key autoincrement, item %s", gsTable, gsLocal_1));
    }
    public void deleteItem(int itemID){
        deleteItem(String.format("%d", itemID));
    }
    public void deleteItem(String itemID){
        String[] selectionArgs = {itemID};
        mSQLiteDatabase.delete(gsTable, "item = ?", selectionArgs);
    }

    public void setItem(int itemID, Object object){
        setItem(String.format("%d", itemID), object);
    }
    public void setItem(String itemID, Object object){
        if (getItem(itemID) == null){
            addItem(itemID, object);
        }else {     // 修改
            String[] columns = {"item"};                    // 需要查询的列
            String selection = "item = ?";                  // 选择条件，给null查询所有
            String[] selectionArgs = {itemID};                // 选择条件参数,会把选择条件中的？替换成这个数组中的值
            ContentValues values = new ContentValues();
            values.put("bean", objectToByte(object));
            mSQLiteDatabase.update(gsTable, values, selection, selectionArgs);
        }
    }
    public void addItem(int itemID, Object object){
        addItem(String.format("%d", itemID), object);
    }
    public void addItem(String itemID, Object object){
        ContentValues values = new ContentValues();
        values.put("item", itemID);
//        MSTRING("CBeanFile addItem A " + objectToByte(object).length);
        values.put("bean", objectToByte(object));
        mSQLiteDatabase.insert(gsTable, null, values);   // 插入一条数据
    }

    public Object getItem(int itemID){
        return getItem(String.format("%d", itemID));
    }
    public Object getItem(String itemID){
        String[] columns = {"item,bean"};               // 需要查询的列
        String selection = "item = ?";                  // 选择条件，给null查询所有
        String[] selectionArgs = {itemID};                // 选择条件参数,会把选择条件中的？替换成这个数组中的值
        String groupBy = null;                          // 分组语句 group by name  注意些的时候需要要group by 去掉
        String having = null;                           // 过滤语句 orderBy = 排序
        String orderBy = null;                          // 排序
        Cursor cursor = mSQLiteDatabase.query(gsTable, columns, selection, selectionArgs, groupBy, having, orderBy);
        Object object = null;
//        MSTRING("getItem A "+itemID);
        if (cursor.moveToFirst()) {
//            MSTRING("getItem B "+itemID);
            int column = cursor.getColumnIndex("bean");
            if (column >= 0){
                object = byteToObject(cursor.getBlob(column));
//                MSTRING("getItem C "+object);
            }
        }
        cursor.close();
        return object;
    }
    public void deleteAllItem(){
        mSQLiteDatabase.delete(gsTable, null, null);
    }
    public List<Object> getList(){
        return getOrgList(Integer.MAX_VALUE, null);
    }
    public List<Object> getOrgList(){
        return getOrgList(Integer.MAX_VALUE, null);
    }
    public List<Object> getDescList(){
        return getOrgList(Integer.MAX_VALUE, "item desc");
    }
    public List<Object> getOrgList(int maxLength, String orderBy){
        List<Object> list = new ArrayList<>();
        Cursor cursor = mSQLiteDatabase.query(gsTable, null, null, null, null, null, orderBy);
        if (cursor.moveToFirst()) {
            int column;
            int counter = 0;
            do {
                column = cursor.getColumnIndex("bean");
                if (column >= 0) {
                    list.add(byteToObject(cursor.getBlob(column)));
                }
                if (++counter >= maxLength){
                    break;
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
        return list;
    }
    public int getSize(){
        Cursor cursor = mSQLiteDatabase.query(gsTable, null, null, null, null, null, null);
        int counter = 0;
        if (cursor.moveToFirst()) {
            do {
                ++counter;
            } while (cursor.moveToNext());
        }
        cursor.close();
        return counter;
    }

    public boolean isExistItem(String itemID){
        String[] columns = {"item"};                    // 需要查询的列
        String selection = "item = ?";                  // 选择条件，给null查询所有
        String[] selectionArgs = {itemID};                // 选择条件参数,会把选择条件中的？替换成这个数组中的值
        Cursor cursor = mSQLiteDatabase.query(gsTable, columns, selection, selectionArgs, null, null, null);
        if (cursor.moveToFirst()) {
            cursor.close();
            return true;
        }
        cursor.close();
        return false;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists User");
        onCreate(db);
    }
    private byte[] objectToByte(Object object){
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
            oos.flush();
            bytes = bos.toByteArray ();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new IllegalArgumentException("CBeanFile objectToByte need implements Serializable");
        }
//        MSTRING("objectToByte C "+bytes.length);
        return bytes;
    }
    public Object byteToObject(byte[] bytes){
        Object object = null;
        if (bytes != null) {
            try {
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bis);
                object = ois.readObject();
                ois.close();
                bis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
        }
//        MSTRING("byteToObject A "+object);
        if (object != null && object instanceof BSaveBean) {
            ConvBean convBean = new ConvBean();
            return convBean.fromSaveBean((BSaveBean) object);
        }
        return object;
    }

}
